package Java进阶.NIO设计的初衷;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 *  tomcat 服务器的设计思路就是使用了NIO
 * 
 */
public class TomcatServer {

	public static void main(String[] args) {
		
		try {
			
			//要使用CopyOnWriteArrayList,不然移除客户端会报异常
			List<SocketChannel> channelList = new CopyOnWriteArrayList<SocketChannel>();
			
			ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
			SocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 8888);
			
			//绑定ip地址和端口号
			serverSocketChannel.bind(socketAddress);
			
			//设置为非阻塞
			serverSocketChannel.configureBlocking(false);
			
			ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
			
			while(true) {
				
				for(SocketChannel socketChannel : channelList) {
					
					//当数据量大于1024的时候,name只会读取ByteBuffer大小的数据
					int len = socketChannel.read(byteBuffer);
					
					//若客户端没有发消息过来,则跳过
					if(len == 0) continue;
					
					//若断开连接,则移除客户端
					if(len == - 1) {
						System.out.println("移除一个客户端 , 当前客户端数量 : " + channelList.size());
						channelList.remove(socketChannel);
						continue;
					}
					
					/*若有内容则输出*/
					byteBuffer.flip();
					
					byte[] b = new byte[len];
					byteBuffer.get(b);
					System.out.println(new String(b));
					
					byteBuffer.flip();
				}
				
				SocketChannel socketChannel  = serverSocketChannel.accept();
				
				if(socketChannel == null) continue;
				
				//设置客户端连接为非阻塞
				socketChannel.configureBlocking(false);
				
				channelList.add(socketChannel);
				
				System.out.println("新连接一个客户端 , 当前客户端数量 : " + channelList.size());
				
				
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		
	}
	
	
	
}
